import {IGitSourceParams} from './git-source-params'
import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs'
import * as util from './util'
import * as authUtil from './auth-helper'
import os from 'os'

export async function getInputs(): Promise<Array<IGitSourceParams>> {
    let resultArray = new Array<IGitSourceParams>()

    let workDir = process.env['WORK_SPACE']
    if (workDir === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'WORK_SPACE'"
        )
        throw new Error("missing workspace 'WORK_SPACE'")
    }
    let sources = process.env['SOURCES']
    if (sources === undefined) {
        step.error(
            "Failed to get params, can not resolve params from 'SOURCES'"
        )
        throw new Error("resolve 'SOURCES' failed")
    }
    let array = JSON.parse(sources)
    //step.info(`source info is ${sources}`)

    //clean workspace
    if (fs.existsSync(`${workDir}${util.SEP}params`)) {
        fs.unlinkSync(`${workDir}${util.SEP}params`)
    }
    if (fs.existsSync(`${workDir}${util.SEP}commitInfo`)) {
        fs.unlinkSync(`${workDir}${util.SEP}commitInfo`)
    }
    if (fs.existsSync(`${workDir}${util.SEP}stepContext`)) {
        fs.unlinkSync(`${workDir}${util.SEP}stepContext`)
    }

    for (let i = 0; i < array.length; i++) {
        let result = new IGitSourceParams()
        let obj = array[i]
        let data = obj.data
        result.workDir = workDir
        result.order = obj.order
        result.type = obj.type
        result.projectDir = workDir + util.SEP + obj.name
        result.name = obj.name
        result.gitRepo = data.repo
        result.repo = data.repo
        result.branch = data.branch
        result.commitId = data.commitId
        result.previousCommitId = data.previousCommitId
        if (data.submodule === undefined) {
            result.submodule = false
        } else {
            result.submodule = data.submodule
        }

        if (data.cloneDepth === undefined) {
            result.depth = 0
        } else {
            result.depth = data.cloneDepth
        }
        if (data.branchMode === undefined) {
            result.branchMode = false
        } else {
            result.branchMode = data.branchMode
        }
        if (result.type === 'flow') {
            result.token = data.token
            result.packages = data.packages
        } else if (result.type === 'jenkins') {
            result.host = data.host
            result.jobPath = data.jobPath
        } else if (result.type === 'packages') {
            result.token = data.token
            result.repoType = data.repoType
            result.repoId = data.repo
            result.artifactName = data.artifactName
            result.versionName = data.versionName
            result.orgId = data.orgId
            result.repoUrl = data.repoUrl
            result.packagesFilePath = data.packagesFilePath
            result.packagesDownloadUrl = `${result.repoUrl}/${result.repoType}/${result.repoId}/artifacts?artifactName=${result.artifactName}&version=${result.versionName}`
        }

        let hostGitMethod = data.method
        if (data.method === undefined || data.method === 'null') {
            hostGitMethod = 'http'
        }
        result.hostGitMethod = hostGitMethod

        let hostGitPK = data.sshPrivateKey
        if (hostGitMethod === 'ssh' && hostGitPK != undefined) {
            authUtil.writePrivateKey(`${workDir}${util.SEP}tempssh`, 'id_rsa_custom', hostGitPK)

            // 兼容子模块 clone 时默认引用 ~/.ssh/id_rsa 文件
            if (process.env['NODEGROUP_TYPE'] === 'K8S') {
                authUtil.writePrivateKey(`${os.homedir()}${util.SEP}.ssh`, 'id_rsa', hostGitPK)
            }
        }
        result.hostGitPK = hostGitPK

        result.user = data.userName
        result.password = data.password
        result.httpUrlWithCredential = false
        result.sshUrl = false

        result.gitEndpoint = authUtil.getGitEndpoint(result.gitRepo)
      
        result.httpPolicy = authUtil.getHttpPolicy(result.gitRepo, result.type)

        resultArray.push(result)
    }
    return resultArray
}
